package com.yjq.programmer;

import org.opencv.core.Point;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;

/**
 * @author 杨杨吖
 * @QQ 823208782
 * @WX yjqi12345678
 * @create 2025-08-16 7:33
 */
public class Level {


    private static final Logger log = LoggerFactory.getLogger(App.class);

    public static void loadOpencv() {
        // 加载opencv库
        System.load(new File("src/main/resources/dll/opencv_java490.dll").getAbsolutePath());
    }

    public static Mat desktopMat(Robot robot) {
        Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        BufferedImage bi = robot.createScreenCapture(screenRect);

        // 确保使用正确的图像类型
        if (bi.getType() != BufferedImage.TYPE_3BYTE_BGR) {
            BufferedImage newBi = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
            Graphics2D g = newBi.createGraphics();
            g.drawImage(bi, 0, 0, null);
            g.dispose();
            bi = newBi;
        }

        // 直接从BufferedImage获取数据
        byte[] data = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
        Mat mat = new Mat(bi.getHeight(), bi.getWidth(), CvType.CV_8UC3);
        mat.put(0, 0, data);
        return mat;
    }

    public static org.opencv.core.Point findImage(Mat src, Mat template) {
        // 创建结果图像
        Mat result = new Mat();
        // 进行模板匹配
        Imgproc.matchTemplate(src, template, result, Imgproc.TM_CCOEFF_NORMED);

        // 设置匹配阈值
        double threshold = 0.6;

        // 在原始图像中寻找匹配结果
        Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
        org.opencv.core.Point maxLoc = mmr.maxLoc;
        log.info("相似度：{}", mmr.maxVal);
        if (mmr.maxVal >= threshold) {
            // 计算匹配区域的右下角坐标
            org.opencv.core.Point matchLoc = new org.opencv.core.Point(maxLoc.x + template.cols(), maxLoc.y + template.rows());
            org.opencv.core.Point center = new org.opencv.core.Point((maxLoc.x + matchLoc.x) / 2, (maxLoc.y + matchLoc.y) / 2);
            Imgproc.circle(src, center, 20, new Scalar(0, 0, 255), -1);
            return center;
        } else {
            throw new RuntimeException("没有搜索到目标图标");
        }
    }

    public static void move(Robot robot, org.opencv.core.Point point) {
        robot.mouseMove(-1, -1);
        int targetX = (int) point.x;
        int targetY = (int) point.y;
        robot.mouseMove(targetX / 2, targetY / 2);
        robot.delay(100);
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        robot.delay(50);
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
    }
    public static void main(String[] args) {
        try {
            int initCount = 20;
            int count = initCount;
            loadOpencv();
            Robot robot = new Robot();
            Point center;
            Mat desktop;
            while (true) {
                desktop = desktopMat(robot);
                log.info("开始扫描精灵...");
                try {
                    // 读取精灵图片
                    Mat img1 = Imgcodecs.imread("src/main/resources/images/level/52.png");
                    center = findImage(desktop, img1);
                    move(robot, center);
                    log.info("找到目标精灵...");
                    Thread.sleep(6000);
                    // 点击手下留情
                    desktop = desktopMat(robot);
                    Mat jineng = Imgcodecs.imread("src/main/resources/images/level/jineng.png");
                    center = findImage(desktop, jineng);
                    move(robot, center);
                    log.info("使用技能...");
                    count--;
                    Thread.sleep(6000);
                    int confirmCount = 0;
                    while(true) {
                        // 点击确定
                        confirmCount++;
                        String url = "";
                        if(confirmCount == 1) {
                            url = "src/main/resources/images/level/confirm.png";
                        } else if (confirmCount == 2) {
                            url = "src/main/resources/images/level/confirm-hover.png";
                        } else {
                            url = "src/main/resources/images/level/cube-confirm-hover.png";
                        }
                        desktop = desktopMat(robot);
                        Mat confirm = Imgcodecs.imread(url);
                        try {
                            if(confirmCount == 2) {
                                try {
                                    center = findImage(desktop, confirm);
                                } catch (Exception ew) {
                                    desktop = desktopMat(robot);
                                    Mat c = Imgcodecs.imread("src/main/resources/images/level/2.png");
                                    center = findImage(desktop, c);
                                    confirmCount--;
                                }
                            } else {
                                center = findImage(desktop, confirm);
                            }
                            move(robot, center);
                            log.info("找到确认按钮...");
                            Thread.sleep(1000);


                        } catch (Exception e) {
                            if(count == 0) {
                                // 找到背包
                                desktop = desktopMat(robot);
                                Mat beibao = Imgcodecs.imread("src/main/resources/images/level/beibao.png");
                                center = findImage(desktop, beibao);
                                move(robot, center);
                                log.info("找到背包...");
                                Thread.sleep(1000);
                                // 恢复精灵
                                desktop = desktopMat(robot);
                                Mat huifu = Imgcodecs.imread("src/main/resources/images/level/huifu.png");
                                center = findImage(desktop, huifu);
                                move(robot, center);
                                log.info("找到恢复按钮...");
                                Thread.sleep(1000);
                                // 确认恢复
                                desktop = desktopMat(robot);
                                Mat confirmHuiFu = Imgcodecs.imread("src/main/resources/images/level/confirm.png");
                                center = findImage(desktop, confirmHuiFu);
                                move(robot, center);
                                log.info("找到确认恢复按钮...");
                                Thread.sleep(1000);
                                // 关闭精灵背包
                                log.info("准备关闭背包...");
                                desktop = desktopMat(robot);
                                Mat close = Imgcodecs.imread("src/main/resources/images/level/close.png");
                                center = findImage(desktop, close);
                                Imgcodecs.imwrite("1.png", desktop);
                                log.info("关闭背包完成...");
                                move(robot, center);
                                log.info("找到关闭精灵背包...");
                                count = initCount;
                            }
                            break;
                        }
                    }

                    Thread.sleep(2000);
                }  catch (Exception e) {
                    //                    e.printStackTrace();
                    try {
                        desktop = desktopMat(robot);
                        Mat confirm = Imgcodecs.imread("src/main/resources/images/level/5.png");
                        center = findImage(desktop, confirm);
                        log.info("精灵不在这个地方了...");
                        move(robot, center);
                    } catch (Exception exx) {
                    }
                }
                Thread.sleep(2000);
            }
        } catch (Exception ex) {
//            ex.printStackTrace();
        }
    }
}
